NSDictionary 的用法
- 1. NSDictionary 的用法
- 2. NSDictionary & NSMutableDictionary Tutorial
- 2.0.1. 1) DIFFERENCE BETWEEN NSDICTIONARY AND NSMUTABLEDICTIONARY
- 2.0.2. 2) HOW TO CREATE NSDICTIONARY WITH KEY AND VALUES
- 2.0.3. 3) CONVERT NSDICTIONARY TO NSMUTABLEDICTIONARY
- 2.0.4. 4) SIZE OF A DICTIONARY
- 2.0.5. 5) ADDING AND REMOVING ENTRIES TO NSMUTABLEDICTIONARY
- 2.0.6. 6) ACCESSING NSDICTIONARY KEY AND VALUES
- 2.0.7. 7) ENUMERATING DICTIONARIES
- 2.0.8. 8) COMPARING DICTIONARIES
- 2.0.9. 9) SORT DICTIONARIES
NSDictionary 的用法
obj-c NSDictionary
NSDictionary & NSMutableDictionary Tutorial
by Ravishanker Kusuma in Tutorials Mar 7th 2014 · 1 Comment
In this Tutorial, I have covered the most useful methods ofNSDictionary and NSMutableDictionary with examples.
Below is the list of examples
1 Difference between NSDictionary and NSMutableDictionary
2) How to create NSDictionary with key and values
3) Convert NSDictionary to NSMutableDictionary
5) Adding and Removing entries to NSMutableDictionary
6) Accessing NSDictionary Key and values
1) DIFFERENCE BETWEEN NSDICTIONARY AND NSMUTABLEDICTIONARY
In Objective-C , NSDictionary is the most common used class. In NSDictionary, Entries are stored in the form of key value pairs. A Dictionary can hold NSNumber, NSString, NSArray, ..etc and their mutable objects.
Below is the simple Dictionary in JSON format.
|1
2
3
4
5
|{ ``"name"``: "Hayagreeva"``, //String ``"age"``: 3, //Number ``"date"``: "2008-02-16T10:06:00Z" //Date}
|
|—–|———————————————————————————————————————————————-|
A bit complex Dictionary is below. Dictionary contains an array,and that array contains dictionary.
|1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|{ ``"name"``: "Hayagreeva"``, //String ``"age"``: 3, //Number ``"subjects"``: { //Array ``"rhymes"``: { //Dictionary 1 ``"test1"``: 10, ``"test2"``: 20, ``"test3"``: 30 ``}, ``"games"``: { //Dictionary 2 ``"test1"``: 40, ``"test2"``: 50, ``"test3"``: 60 ``}, ``"crayoning"``: { //Dictionary 3 ``"test1"``: 70, ``"test2"``: 80, ``"test3"``: 90 ``} ``}, ``"date"``: "2008-02-16T10:06:00Z" //Date}
|
|———————————–|——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————|
Main Difference is:
NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary.
NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).
2) HOW TO CREATE NSDICTIONARY WITH KEY AND VALUES
To create a dictionary you can use static methods, or initialization methods.
|1
2
3
4
5
6
7
8
9
10
11
12
|Static methods``:+ (instancetype)dictionary;+ (instancetype)dictionaryWithObject:(``id``)object forKey``:(``id <NSCopying>)key;+ (instancetype)dictionaryWithObjectsAndKeys:(``id``)firstObject, ... nil``;+ (instancetype)dictionaryWithObjects:(``NSArray *)objects forKeys``:(``NSArray *)keys;+ (instancetype)dictionaryWithDictionary:(``NSDictionary *)dict;
Init Methods``:- (instancetype)init;- (instancetype)initWithObjectsAndKeys:(``id``)firstObject, ... nil``;- (instancetype)initWithObjects:(``NSArray *)objects forKeys``:(``NSArray *)keys;- (instancetype)initWithDictionary:(``NSDictionary *)otherDictionary;
|
|—————|————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————-|
how to create a dictionary example:
|1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|NSString * key``1 =``@"name"``;NSString * obj``1 =``@"Hayagreeva"``;NSString * key``2 =``@"age"``;NSNumber * obj``2 =[``NSNumber numberWithInt``:``3``];
//1.Empty dictionary. @{} dictionary representation and it is not for NSMuableDictionaryNSDictionary * dict``1 =[``NSDictionary dictionary``];NSDictionary * dict``2 =[[``NSDictionary alloc``] init``];NSDictionary * dict``3 = @{};
//2.Dictionary with Single Object and KeyNSDictionary * dict``4 =[``NSDictionary dictionaryWithObject``:obj``1 forKey``:key``1``];NSDictionary * dict``5 =@{key``1``:obj``1``};
//3.Dictionary with Multiple Object and Keys//Objects and keys are sequentially terminated with nilNSDictionary * dict``6 = [NSDictionary dictionaryWithObjectsAndKeys``:obj``1``,key``1``,obj``2``,key``2``,nil];
NSDictionary * dict``7 =[[``NSDictionary alloc``] initWithObjectsAndKeys``:obj``1``,key``1``,obj``2``,key``2``,nil] ;
//3.Dictionary with Multiple Object and KeysNSDictionary *dict``8 =[NSDictionary dictionaryWithObjects``:@[obj``1``,obj``2``] forKeys``:@[key``1``,key``2``]];NSDictionary *dict``9 =[[``NSDictionary alloc``] initWithObjects``:@[obj``1``,obj``2``] forKeys``:@[key``1``,key``2``]];NSDictionary * dict``1``0 =@{key``1``:obj``1``,key``2``:obj``2``};
//@[obj1,obj2] is the array representation. dict6,dict7,dict8 are same.NSDictionary *dict``1``1 =[[``NSDictionary alloc``] initWithObjects``:[``NSArray arrayWithObjects``:obj``1``,obj``2``,nil] forKeys``:[``NSArray arrayWithObjects``:key``1``,key``2``,nil]];
//4.Dictionary with another Dictionary//@[obj1,obj2] is the array representation. dict6,dict7,dict8 are same.NSDictionary *dict``1``2``=[``NSDictionary dictionaryWithDictionary``:dict``8``];NSDictionary *dict``1``3``=[[``NSDictionary alloc``] initWithDictionary``:dict``8``];
|
|———————————————————————–|—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————|
Note: You can use same methods to create NSMutableDictionary. @{} representation is only for NSDictionary.
3) CONVERT NSDICTIONARY TO NSMUTABLEDICTIONARY
NSDictionary is mutable, So if you want to make any modifications to that you need to convert it as NSMutableDictionary and make changes.
To convert NSDictionary to NSMutableDictionary, you can use the method mutableCopy
Example:
|1
2
3
4
5
6
7
8
9
|NSDictionary * dict = [NSDictionary dictionaryWithObjects``:@[``@"Ravi"``,``@"33"``,``@"India"``,``@"India"``] forKeys``:@[``@"name"``,``@"age"``,``@"location"``,``@"country"``]];//You can not do this//[dict setValue:@"XXX" forKey:@"YYY"];
NSDictionary * mutable =[dict mutableCopy``];//You set value[mutable setValue``:``@"XXX" forKey``:``@"YYY"``];
|
|———|——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————|
4) SIZE OF A DICTIONARY
You can use count properity to get the size of a dictionary. Below is the example.
|1
2
|NSDictionary *dict =[[``NSDictionary alloc``] initWithObjects``:@[``@"Ravi"``,``@"33"``] forKeys``:@[``@"name"``,``@"age"``]];NSLog(``@"Dictionary Size =%d"``,dict``.count``);
|
|–|——————————————————————————————————————————————————————————————-|
5) ADDING AND REMOVING ENTRIES TO NSMUTABLEDICTIONARY
5.1) Adding Entries
You can add entries to NSMutableDictionary using the following methods:
|1
2
3
4
|- (``void``)setObject:(``id``)anObject forKey``:(``id <NSCopying>)aKey;- (``void``)setObject:(``id``)obj forKeyedSubscript``:(``id <NSCopying>)key NS_AVAILABLE(``1``0``_``8``, 6``_``0``);- (``void``)addEntriesFromDictionary:(``NSDictionary *)otherDictionary;- (``void``)setValue:(``id``)value forKey``:(``NSString *)key;
|
|—-|——————————————————————————————————————————————————————————————————————————————————————————————————————————————————–|
Example:
|1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|NSMutableDictionary *dict =[[``NSMutableDictionary alloc``] init``];//1. using setValue[dict setValue``:``@"Hayagreeva" forKey``:``@"name"``];
//2. using setObject[dict setObject``:[``NSNumber numberWithInt``:``3``] forKey``:``@"age"``];[dict setObject``:[``NSDate date``] forKey``:``@"date"``];
//3 adding entries using subscriptdict[``@"city"``]=``@"Hyderabad"``;
//3). Adding Objects from Another Dictionary[dict addEntriesFromDictionary``:[NSMutableDictionary dictionaryWithObjectsAndKeys``: ``@"India"``,``@"location"``, nil``]];
|
|———————|————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————|
5.1) Removing Entries
You can remove entries from NSMutableDictionary using the following methods.
|1
2
3
|- (``void``)removeObjectForKey:(``id``)aKey;- (``void``)removeObjectsForKeys:(``NSArray *)keyArray;- (``void``)removeAllObjects;
|
|—|—————————————————————————————————————————————-|
Example:
|1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|NSMutableDictionary * dict = [NSMutableDictionary ``dictionaryWithObjects:@[@``"Ravi"``,@``"33"``,@``"India"``,@``"India"``] ``forKeys:@[@``"name"``,@``"age"``,@``"location"``,@``"country"``]];
//1``. Remove entry with given key[dict removeObjectForKey:@``"city"``];
NSLog(@``"Dict =%@"``,dict);
//2``. Remove Entries with given keys.[dict removeObjectsForKeys:@[@``"location"``,@``"age"``]];
NSLog(@``"Dict =%@"``,dict);
//3``. Remove all the entries[dict removeAllObjects];NSLog(@``"Dict =%@"``,dict);
|
|————————-|———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————|
6) ACCESSING NSDICTIONARY KEY AND VALUES
5.1) Access Values using with Given key
Values are accessed using array subscript or objectForKey method. List of methods for accessing keys and values.
|1
2
3
4
5
6
7
|- (``id``)objectForKey:(``id``)aKey;- (``id``)valueForKey:(``NSString *)key;
//to access all keys or objects- (``NSArray *)allValues;- (``NSArray *)allKeys;- (``NSArray *)allKeysForObject:(``id``)anObject;
|
|——-|———————————————————————————————————————————————————————————————————————————|
Example:
|1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithObjects``:@[``@"Ravi"``,``@"33"``,``@"India"``,``@"India"``] forKeys``:@[``@"name"``,``@"age"``,``@"location"``,``@"country"``]]; ``//1.using objectForKey ``NSString * name = [dict objectForKey``:``@"name"``];
``//2. using array subscript ``NSString * location = dict[``@"location"``];
``//3. using valueForKey ``NSString * age =[dict valueForKey``:``@"age"``];
``//4. Access all the values as array ``NSArray * values =[dict allValues``]; ``for (``id value in values) { ``NSLog(``@"value =%@"``,value); ``}
``//5. Access all the keys ``NSArray * keys =[dict allKeys``];
``for``(``NSString * key in keys) ``{ ``NSString * value =[dict objectForKey``:key]; ``NSLog(``@"key=%@, value=%@"``,key, value); ``}
``//6. Access keys with given object ``NSArray * skeys =[dict allKeysForObject``:``@"India"``]; ``for (``NSString * key in skeys) { ``NSLog(``@"key =%@"``,key); ``}
|
|——————————————————-|——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————–|
7) ENUMERATING DICTIONARIES
To enumerate Dictionaries, you can use the following the methods:
|1
2
3
4
|- (``NSEnumerator *)keyEnumerator;- (``NSEnumerator *)objectEnumerator;- (``void``)enumerateKeysAndObjectsUsingBlock:(``void (^)(``id key, id obj, BOOL *stop))block NS_AVAILABLE(``1``0``_``6``, 4``_``0``);- (``void``)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts usingBlock``:(``void (^)(``id key, id obj, BOOL *stop))block NS_AVAILABLE(``1``0``_``6``, 4``_``0``);
|
|—-|————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————–|
Example:
|1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithObjects``:@[``@"33"``,``@"India"``,``@"India"``,``@"Ravi"``] forKeys``:@[``@"age"``,``@"location"``,``@"country"``,``@"name"``]];
//Enumerator using keysNSEnumerator *kEnumerator = [dict keyEnumerator``];id key=nil;while``(key =[kEnumerator nextObject``]){ ``NSLog(``@"Key =%@"``,key);}
//Enumerator using valuesNSEnumerator *oEnumerator = [dict objectEnumerator``];id value=nil;while``(value =[oEnumerator nextObject``]){ ``NSLog(``@"Value =%@"``,value);}
//Enumerate using code block[dict enumerateKeysAndObjectsUsingBlock``:^(``id key, id obj, BOOL *stop){ ``NSLog(``@"%@:%@"``,key,obj);}];
|
|—————————————–|————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————|
8) COMPARING DICTIONARIES
isEqualToDictionary method is used to compare dictionaries. It returns YES, if two dictionaries
are equal.
Example:
|1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|NSMutableDictionary * dict``1 = [NSMutableDictionary dictionaryWithObjects``:@[``@"Ravi"``,``@"33"``,``@"India"``,``@"India"``] forKeys``:@[``@"name"``,``@"age"``,``@"location"``,``@"country"``]];NSMutableDictionary * dict``2 = [NSMutableDictionary dictionaryWithObjects``:@[``@"33"``,``@"India"``,``@"India"``,``@"Ravi"``] forKeys``:@[``@"age"``,``@"location"``,``@"country"``,``@"name"``]];
NSMutableDictionary * dict``3 = [NSMutableDictionary dictionaryWithObjects``:@[``@"Hayagreeva"``,``@"2"``,``@"India"``,``@"India"``] forKeys``:@[``@"name"``,``@"age"``,``@"location"``,``@"country"``]];if``([dict``1 isEqualToDictionary``:dict``2``]){ ``NSLog(``@" dict 1 and dict 2 are equal"``);}if``(![dict``1 isEqualToDictionary``:dict``3``]){ ``NSLog(``@" dict 1 and dict 3 are not equal"``);}
|
|—————————|—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————|
9) SORT DICTIONARIES
We can sort the dictionaries using the following methods.
|1
2
3
|- (``NSArray *)keysSortedByValueUsingSelector:(``SEL``)comparator;- (``NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr NS_AVAILABLE(``1``0``_``6``, 4``_``0``);- (``NSArray *)keysSortedByValueWithOptions:(NSSortOptions)opts usingComparator``:(NSComparator)cmptr NS_AVAILABLE(``1``0``_``6``, 4``_``0``);
|
|—|———————————————————————————————————————————————————————————————————————————————————————————————————————————————-|
Sort NSDictionary example:
|1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|NSMutableDictionary * services = [[``NSMutableDictionary alloc``] init``];[services setObject``:``@"Mail" forKey``:``@"Yahoo"``];[services setObject``:``@"Windows" forKey``:``@"Microsoft"``];[services setObject``:``@"Social" forKey``:``@"Facebook"``];[services setObject``:``@"Search" forKey``:``@"Google"``];
//sort by valuesNSArray * keys = [services keysSortedByValueUsingComparator``: ``^NSComparisonResult(``id obj``1``, id obj``2``) {
``//return [obj2 compare:obj1]; //descending ``return [obj``1 compare``:obj``2``]; //ascending ``}];for``(``NSString *key in keys){ ``NSLog(``@"%@:%@"``,key,[services objectForKey``:key]);}
//Sort using Default comparatorNSArray * keys``2 = [services keysSortedByValueUsingSelector``:``@selector``(compare:)];for``(``NSString *key in keys``2``){ ``NSLog(``@"%@:%@"``,key,[services objectForKey``:key]);}
|
|—————————————–|—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————-|
If you want to use custom selector method with keysSortedByValueUsingSelector , you need to add that method inNSString using Categories. Below is the code.
|1
2
3
4
5
6
7
8
|@implementation NSString (Sort)//compare starts from second character.ignore first character- (NSComparisonResult)customeCompare:(``NSString *)string{ ``NSString * str``1 =[``self substringFromIndex``:``1``]; ``NSString * str``2 = [string substringFromIndex``:``1``]; ``return [str``1 compare``:str``2``];}
|
|——–|—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————–|

